import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import viteCompression from 'vite-plugin-compression';
import crypto from 'crypto';

const getMD5 = (content:string) => {
  return crypto.createHash('md5').update(content).digest('hex').substring(0, 8);
}

export default defineConfig({
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  server:{
    open:true,
    port: 5174,
    host: '0.0.0.0',
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@import '@/assets/css/common.scss'; @import '@/assets/css/element.scss';@import '@/theme/index.scss';`
      }
    }
  },
  build:{
    cssCodeSplit: true,
    rollupOptions: {
      output: {
        entryFileNames: (chunk) => {
          const mName = chunk.name;
          return `assets/${getMD5(mName)}.[hash].js`;
        },
        chunkFileNames:(chunk) => {
          const mName = chunk.name;
          return `assets/${getMD5(mName)}.[hash].js`;
        },
        assetFileNames: (chunk) => {
          const mName = chunk.name ?? '';
          return `assets/${getMD5(mName)}.[hash].[ext]`;
        },
      },
    },
  },
  plugins: [
    vue(),
    viteCompression({
      verbose: true, // 默认即可
      disable: false, //开启压缩(不禁用)，默认即可
      deleteOriginFile: false, //删除源文件
      threshold: 10240, //压缩前最小文件大小
      algorithm: 'gzip', //压缩算法
      ext: '.gz', //文件类型
    })
  ],
})
